package com.renfei.multimediatask.ui.task2;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.renfei.multimediatask.R;
import com.renfei.multimediatask.base.BaseActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * step1   权限 permission.AudioRecord   读写存储权限
 */
public class RecordPcmDataActivity extends BaseActivity {


    @BindView(R.id.tv_record_prompt)
    TextView tvRecordPrompt;
    @BindView(R.id.startRecord)
    Button startRecord;
    @BindView(R.id.stopRecord)
    Button stopRecord;
    @BindView(R.id.ll_btn_layout)
    RelativeLayout llBtnLayout;
    @BindView(R.id.tv_file_path)
    TextView tvFilePath;
    @BindView(R.id.tv_file_path_values)
    TextView tvFilePathValues;

    private RecordThread recordThread;

    //文件存储地址
    private File targetFile;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_record_pcm_data;
    }

    @Override
    protected void initListener() {
        recordThread = new RecordThread(new WeakReference<>(this));


        try {
//            File tmpFile = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
//            String targetFilePath = tmpFile.getPath() + "test_record.pcm";
            String targetFilePath = getParentFilePath() + "test_record.pcm";
            targetFile = new File(targetFilePath);
            if (targetFile.exists()) {
                targetFile.delete();
            }
            if (!targetFile.createNewFile()) {
                Log.e("RecordPcmDataActivity", "文件创建失败");
                return;
            }
            ;
        } catch (IOException e) {
            e.printStackTrace();
        }

        tvFilePathValues.setText(targetFile.getPath());
    }


    @OnClick({R.id.startRecord, R.id.stopRecord})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.startRecord:
                start();
                break;
            case R.id.stopRecord:
                stop();
                break;
        }
    }

    private void stop() {
        if (null != recordThread) {
            recordThread.stopRecording();
        }
    }

    private void start() {
        if (null != recordThread) {
            recordThread.start();
        }
    }


    static class RecordThread extends Thread {
        //录音来源
        private int audioSource = MediaRecorder.AudioSource.MIC;
        //采样率
        private int sampleRateInHz = 44100;
        //声道 左声道、右声道、立体声
        private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
        //采样位数
        private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        // int：记录期间写入音频数据的缓冲区的总大小（以字节为单位）。
        // 请参见getMinBufferSize（int，int，int）以确定成功创建AudioRecord实例所需的最小缓冲区大小。
        private int bufferSizeInBytes;

        private WeakReference<RecordPcmDataActivity> weakReference;
        private AudioRecord audioRecord;

        private boolean isRecord = false;

        public RecordThread(WeakReference<RecordPcmDataActivity> weakReference) {
            this.weakReference = weakReference;

            bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
            audioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);

            Log.e("RecordThread 初始化时 ", audioRecord.getState() + "");
        }


        @Override
        public void run() {
            super.run();
            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                Log.e("RecordThread ", audioRecord.getState() + "");
                return;
            }


            isRecord = true;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(weakReference.get().targetFile);
                audioRecord.startRecording();
                byte[] byteBuffer = new byte[bufferSizeInBytes];

                while (isRecord) {
                    int size = audioRecord.read(byteBuffer, 0, byteBuffer.length);
                    Log.e("RecordThread ", "文件写入中...     写入长度    " + size);
                    fos.write(byteBuffer, 0, size);
                    fos.flush();
                }
                //读取完成后，停止录音
                audioRecord.stop();
            } catch (IOException e) {
                e.printStackTrace();

                if (null != audioRecord) {
                    isRecord = false;
                    audioRecord.release();
                    audioRecord = null;
                }
            }
            //正常结束后， 录音状态设置为false
            if (null != audioRecord) {
                isRecord = false;
                audioRecord.release();
                audioRecord = null;
            }
        }

        public void stopRecording() {
            isRecord = false;
        }
    }
}
